package com.fare.taluo.message;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.fare.taluo.message.exception.MessageException;
import com.huawei.ema.gd.webservice.Message;
/**
 * SMS短信消息发送
 * <p>该实现类可能还存在问题，因为在开发完成后，还没有测试环境进行验证
 * <p>在hawei提供的sms.jar包上进行二次封装，该对象在实例化时即会创建新的{@link Message}对象
 * <p>提供两个方法setAccount()设置目标帐号，setContent()设置发送内容, 依赖于{@link SMSSoapService#send(Message)}发送消息
 * <p>示例: new SendSMS().setAccount("13535552888").setContent("有事没事请打电话").send();
 * @author xiangsf 2012-12-9
 *
 */
public class SendSMS {
	
	protected Logger logger = Logger.getLogger(getClass());
	//短信配置属性
	private SMSMessageProperties configuration;
	private SMSSoapService smsSoapService;
	private Message message = new Message();
	public SendSMS(){
		
		this.configuration = MessageConfiguration.getInstance().getSmsProperties();
		try {
			smsSoapService = SMSSoapService.getInstance().init(configuration);//在已进行过初始化后，不会再进行初始化
			//登陆失败时，token为空
			if(StringUtils.isEmpty(smsSoapService.getToken())) 
				this.configuration.setSmsServerSwitch(false); //将开关置为否
		} catch (Exception e) {
			logger.error("初始化短信服务失败!系统自动停止短信服务!", e);
			this.configuration.setSmsServerSwitch(false); //将开关置为否
		}
	}
	/**
	 * 设置发送的目标帐号（手机号）
	 * @param account
	 * @return
	 */
	public SendSMS setAccount(String account){
		if(configuration.isSmsServerSwitch()){
			MessageAssert.hasText(account, "发送消息的目标帐号");
			message.setAccount(account);
		}
		return this;
	}
	/**
	 * 设置发送的内容
	 * @param text
	 * @return
	 */
	public SendSMS setContent(String text){
		if(configuration.isSmsServerSwitch()){
			MessageAssert.hasText(text, "发送消息内容");
			message.setText(text);
		}
		return this;
	}

	/**
	 * 发送消息(短信)
	 * @throws MessageException
	 */
	public void send() throws MessageException {
		if(configuration.isSmsServerSwitch()){
			try {
				if(logger.isDebugEnabled()){
					logger.debug(String.format("发送短信给[%s],内容是[%s]。", message.getAccount(), message.getText()));
				}
				MessageAssert.hasText(message.getAccount(), "发送消息的目标帐号");
				MessageAssert.hasText(message.getText(), "发送消息内容");
				message.setSystemId(MessageConfiguration.getInstance().getSystemIdentity());
				this.smsSoapService.send(message);
			} catch (Exception e) {
				logger.error(e);
				throw new MessageException(e);
			}
		}
	}
}
